package com.juzhencms.apps.busi.web;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.juzhencms.apps.base.common.config.Config;
import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.base.common.util.StringUtil;
import com.juzhencms.apps.base.common.util.WebUtil;
import com.juzhencms.apps.busi.service.AppWeixinSourceService;
import com.juzhencms.apps.busi.service.SiteService;

import lombok.extern.slf4j.Slf4j;


@Controller
@RequestMapping("/appReply")
@Slf4j
public class AppReplyController  extends BaseController{
	
	@Autowired
	private AppWeixinSourceService appWeixinSourceService;
	@Autowired
	private SiteService siteService;
	@RequestMapping(value="/gridlistData",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String gridlistData(HttpServletRequest request){
		Map data=new HashMap();
		List whereParamList=new ArrayList();
		String where="where del_flag=0 and site_id in("+this.getUserService().getLoginUser().getSiteIds()+") ";
		//搜索参数
		if(request.getParameter("site_id")!=null && !request.getParameter("site_id").toString().trim().equals("")){
			where+=" and site_id =? ";
			whereParamList.add(request.getParameter("site_id"));
		}else {
			where+=" and site_id =0 ";
		}
		//type
		if(request.getParameter("type")!=null && !request.getParameter("type").toString().trim().equals("")){
			where+=" and type =? ";
			whereParamList.add(request.getParameter("type"));
		}
		if(request.getParameter("publish")!=null && !request.getParameter("publish").toString().trim().equals("")){
			where+=" and publish = ? ";
			whereParamList.add(request.getParameter("publish"));
		}
		if(request.getParameter("varValue")!=null && !request.getParameter("varValue").toString().trim().equals("")){
			if(request.getParameter("searchVar")!=null && !request.getParameter("searchVar").toString().trim().equals("")){
				String searchVar=request.getParameter("searchVar");
				whereParamList.add("%"+request.getParameter("varValue")+"%");
				where += " and "+searchVar+" like ? ";
			}
		}
		//分页处理
		int pageIndex=1;
		if(request.getParameter("pageIndex")!=null && !request.getParameter("pageIndex").toString().trim().equals("")){
			pageIndex=new Integer(request.getParameter("pageIndex")).intValue();
		}
		int pageSize=10;
		if(request.getParameter("pageSize")!=null && !request.getParameter("pageSize").toString().trim().equals("")){
			pageSize=new Integer(request.getParameter("pageSize")).intValue();
		}
		int start=0;
		if(pageIndex>1){
			start=(pageIndex-1)*pageSize;
		}
		whereParamList.add(start);
		whereParamList.add(pageSize);
		
		//排序参数 
		String sortField="position";
		String sortOrder="asc";
		if(request.getParameter("sortField")!=null && !request.getParameter("sortField").equals(""))
			sortField = request.getParameter("sortField");
		if(request.getParameter("sortOrder")!=null && !request.getParameter("sortOrder").equals(""))
			sortOrder = request.getParameter("sortOrder");
		
		//查询列表数据
		List dataList=this.getCommonService().getJdbcDao().querySql("select * from "+DBTable.appReply+" "+where+" order by "+sortField+" "+sortOrder+" limit ?,?", whereParamList.toArray());
		if(dataList!=null && dataList.size()>0){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for(int i=0;i<dataList.size();i++){
				Map row=(Map)dataList.get(i);
				if(row.get("create_time")!=null) {
					Date date = (Date)row.get("create_time");
					row.put("create_time",sdf.format(date));
				}
			}
		}
		
		//查询总条数
		Map countRow=this.getCommonService().getJdbcDao().queryRow("select count(id) as count_num from "+DBTable.appReply+" "+where, whereParamList.subList(0, whereParamList.size()-2).toArray());
		int recordsTotal=0;
		if(countRow.get("count_num")!=null){
			recordsTotal=new Integer(countRow.get("count_num").toString()).intValue();
		}
		
		//拼装返回的数据
		data.put("data", dataList.toArray());
		data.put("itemsCount", recordsTotal);
		
		
		return WebUtil.resultString(data,request);
	}
	
	@RequestMapping(value="/detailData/{id}",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String detailData(@PathVariable("id") String id,HttpServletRequest request){
		Map data=new HashMap();
		Map record=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.appReply+" where del_flag=0 and  id=?",new Object[]{id});	
		
		List newsList = new ArrayList();
		if(record!=null && record.size()>0) {
			//查找站点信息，
			int siteID=new Integer(record.get("site_id")+"");
			Map siteInfo=this.siteService.getDetail(siteID, "name");
			record.put("site_name", siteInfo.get("name")+"");
			if(record.get("create_time")!=null) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date date = (Date)record.get("create_time");
				record.put("create_time",sdf.format(date) );
			}		
			if("news".equals(record.get("reply_message_type")+"")) {
				//获取推送的文章
				/*if(StringUtil.isNotNullOrEmpty(record.get("weixin_source_id"))) {
					int weixin_source_id = new Integer(record.get("weixin_source_id")+"");
					newsList=this.appWeixinSourceService.getWeiXinSourceNewsList(weixin_source_id);
				}*/	
				
				String sql="SELECT id,name,hits,publish,recommend,position,create_user,create_time,image FROM "+DBTable.news+" where id=? and del_flag=0";
				newsList=this.getCommonService().getJdbcDao().querySql(sql, new Object[] {record.get("reply_content")});
				if(newsList!=null && newsList.size()>0) {
					for(int i=0;i<newsList.size();i++) {
						Map newsInfo=(Map) newsList.get(i);
						if(StringUtil.isNotNullOrEmpty(newsInfo.get("image"))) {
							newsInfo.put("_image",Config.getUploadUrlPath()+"/"+newsInfo.get("image"));
						}else newsInfo.put("_image",Config.getUploadUrlPath()+"/nophoto.jpg");
					}
				}
				log.info(newsList+"======newsList");
			}else if("text".equals(record.get("reply_message_type")+"")) {
				record.put("click_send_text", record.get("reply_content"));
			}	
			record.put("newsList", newsList);
		}	
		data.put("data", record);
		return WebUtil.resultString(data,request);
	}
	
	@RequestMapping(value="/save",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String save(HttpServletRequest request){
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		String id=null;
		if(data.get("id")!=null){
			id=data.get("id").toString();
		}
		String msg="";
		boolean check = true;
		String type="";
		if(StringUtil.isNotNullOrEmpty(data.get("type")) && !"0".equals(data.get("type")+"")) {
			type=data.get("type")+"";
			/*if(!type.equals("1") && !type.equals("2")) { //关键字回复
				check=false;
				msg="type参数有误，请选择正确的自动回复类型";
			}	*/		
		}else {
			check=false;
			msg="type参数有误，请选择正确的自动回复类型";
		}
		if(StringUtil.isNullOrEmpty(data.get("site_id"))) {
			check=false;
			msg="site_id参数有误，请选择正确的微信公众号";
		}		
		
		Map result=new HashMap();		
		if(!check) {
			result.put("result", 0);
			result.put("msg", msg);			
			return WebUtil.resultString(result,request);
		}
		int  site_id=new Integer(data.get("site_id")+"");
		Map editorNewInfo=new HashMap();
		editorNewInfo.put("publish", data.get("publish"));
		editorNewInfo.put("type", type);
		editorNewInfo.put("keywords", "");
		editorNewInfo.put("name", "");
		editorNewInfo.put("reply_content", "");
		if(StringUtil.isNotNullOrEmpty(data.get("reply_message_type"))) {
			String reply_message_type=data.get("reply_message_type")+"";			
			editorNewInfo.put("reply_message_type", reply_message_type);
			if("news".equals(reply_message_type)) {				
				//把当前选择的文章新增文章素材
				if(data.get("newsList")!=null) {
					List newsList = (List) data.get("newsList");					
					if(newsList!=null && newsList.size()>0) {
						//
						
						Map replyNews=(Map) newsList.get(0);						
						
						editorNewInfo.put("reply_content", replyNews.get("id")); //回复内容填写新闻ID
						
						
						/*Map weiXinNews=this.appWeixinSourceService.addWeiXinNewsSource(site_id, newsList);
						System.out.print("weiXinNews==="+weiXinNews);
						String resultStr = weiXinNews.get("result")+"";
						if(weiXinNews!=null && "1".equals(resultStr)) {
							editorNewInfo.put("reply_content", weiXinNews.get("media_id"));
							editorNewInfo.put("weixin_source_id", weiXinNews.get("id"));
						}else {
							result.put("result", 0);
							result.put("msg", weiXinNews.get("msg"));	
							return WebUtil.resultString(result,request); 
						}*/								
					}				
			   }				
			}else if("image".equals(reply_message_type)) {
				//处理图片消息
				if(StringUtil.isNotNullOrEmpty(data.get("img"))) {						
					Map weiXinImage=this.appWeixinSourceService.addWeinXinImageSource(site_id, data.get("img")+"",null);						
					editorNewInfo.put("reply_content", weiXinImage.get("media_id"));
					editorNewInfo.put("weixin_source_id", weiXinImage.get("id"));						
				}else {
					result.put("msg", "请选择：正确的图片信息");
					return WebUtil.resultString(result,request);
				}
			}else if("text".equals(reply_message_type)) {
				if(StringUtil.isNotNullOrEmpty(data.get("click_send_text"))) {											
					editorNewInfo.put("reply_content",data.get("click_send_text"));
					editorNewInfo.put("weixin_source_id", 0);						
				}else {
					result.put("msg", "请填写回复的文字！");
					return WebUtil.resultString(result,request);
				}				
			}else if("video".equals(reply_message_type)) {
				check=false;
				msg="参数有误，请选择正确的回复内容类型";
			}else if("voice".equals(reply_message_type)) {
				check=false;
				msg="参数有误，请选择正确的回复内容类型";
			}else {
				check=false;
				msg="参数有误，请选择正确的回复内容类型";
			}
		}else {
			check=false;
			msg="参数有误，请选择正确的回复内容类型";
		}		
		if(type.equals("1")) { //关键词回复
			editorNewInfo.put("name", data.get("name"));
			editorNewInfo.put("keywords", data.get("keywords"));
			
			//校验公众号下的关键词不能重复
			Map tmp=this.getCommonService().getJdbcDao().queryRow("select id from "+DBTable.appReply+" where del_flag=0 and site_id=? and id!=? and keywords=? limit 0,1", new Object[] {site_id,id!=null?id:"",data.get("keywords")});
			log.info("select id from "+DBTable.appReply+" where del_flag=0 and site_id=? and id!=? and keywords=? limit 0,1");
			log.info(JSON.toJSONString(new Object[] {site_id,id,data.get("keywords")}));
			log.info(JSON.toJSONString(tmp));
			if(tmp!=null) {
				check=false;
				msg="关键词重复，请检查后再保存";
			}
		}		
		if(!check) {
			result.put("result", 0);
			result.put("msg", msg);			
			return WebUtil.resultString(result,request);
		}		
		if(id==null || id.equals("")){			
            editorNewInfo.put("site_id", site_id);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = new Date();
			editorNewInfo.put("create_time", sdf.format(date));
			this.getCommonService().getJdbcDao().addObj(DBTable.appReply, editorNewInfo);
		}else{
			editorNewInfo.put("id", id);
			this.getCommonService().getJdbcDao().updateObj(DBTable.appReply, editorNewInfo, "id");
		}		
		result.put("result", 1);
		result.put("msg", "保存成功");		
		return WebUtil.resultString(result,request);
	}
	
	@RequestMapping(value="/delete",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String delete(HttpServletRequest request){

		
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		
		String id=null;
		if(data.get("id")!=null){
			id=data.get("id").toString();
		}
		
		
		if(id==null || id.equals("")){
		}else{	
	        String[] idArray = id.split(",");
	        String tmpVar="?";
	        if(idArray!=null && idArray.length>0){
	        	Matcher matcher = Pattern.compile("\\d+").matcher(id);
	        	tmpVar=matcher.replaceAll("?");
	        }
	        
	        
	        
			this.getCommonService().getJdbcDao().updateSql("update "+DBTable.appReply+" set del_flag=1 where id in ("+tmpVar+")",idArray);
		}
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		
		return WebUtil.resultString(result,request);
	}
	
	@RequestMapping(value="/updatePosition",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String updatePosition(HttpServletRequest request){
		
		if(request.getParameter("position")==null || request.getParameter("id")=="")
			return "";
		
		this.getCommonService().getJdbcDao().updateSql("update "+DBTable.appReply+" set position=? where id=?",new Object[]{request.getParameter("position"),request.getParameter("id")});
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		
		return WebUtil.resultString(result,request);
	}
	
	
	
}
